import 'package:flutter/material.dart';
import 'package:riki_router/riki_router.dart';

typedef OnRikiEventTransform<T> = T Function(dynamic value);

class RikiEventNotify<T> extends StatefulWidget {
  const RikiEventNotify({
    Key? key,
    required this.builder,
    required this.eventType,
    required this.initValue,
    this.transform,
    this.child,
  }) : super(key: key);

  final String eventType;
  final T initValue;
  final ValueWidgetBuilder<T> builder;
  final OnRikiEventTransform<T>? transform;
  final Widget? child;

  @override
  State<RikiEventNotify<T>> createState() => _RikiEventNotifyState<T>();
}

class _RikiEventNotifyState<T> extends State<RikiEventNotify<T>> implements RikiEventListener {
  String get package => hashCode.toString();

  late T data;

  @override
  void initState() {
    super.initState();
    data = widget.initValue;
    RikiEvent.instance.addListener(package, this);
  }

  @override
  void dispose() {
    super.dispose();
    RikiEvent.instance.removeListener(this, package: package);
  }

  @override
  Widget build(BuildContext context) {
    return widget.builder(context, data, widget.child);
  }

  @override
  void onRikiEvent(RikiEventType type, arguments, completer) {
    if (type.value == widget.eventType) {
      if (widget.transform != null) {
        data = widget.transform!(arguments);
        setState(() {});
      } else if (arguments is T) {
        data = arguments;
        setState(() {});
      }
    }
  }

  @override
  List<String> get registerEvents => [widget.eventType];
}
